const bodyParser = require('body-parser');
const fs = require("fs")
const Mock = require("mockjs");
const Users = require("./src/user/user.json")
var data = Mock.mock({
    "list|15":[{
        "tit":"@ctitle(5,10)",
        "date":"@dateTime",
        "name":"@cname"
    }]
})
module.exports = {
    devServer:{
        before(app){
            app.use(bodyParser.json());
            app.post("/login",(req,res)=>{
                let {username,password} = req.body
                console.log(username,password)
                // flag 如果是true说明数据库(json)里有这个用户
                let flag =  Users.some((item,index)=>{
                    return item.username == username
                    }   
                )
                // 判断密码输入正确
                if (flag) {
                    let newArr =  Users.some((item,index)=>{
                        return item.password == password && item.username == username
                    }) 
                    if (newArr) {
                        res.send({
                            code:1,
                            msg:"登陆成功"
                        })
                    } else {
                        res.send({
                            code:0,
                            msg:"密码措错误"
                        })
                    }
                } else { // 这个else里是去注册
                    Users.push(req.body)
                    fs.writeFileSync("./src/user/user.json",JSON.stringify(Users))
                    res.send({
                        code:2,
                        msg:"注册成功"
                    })
                }
            })
            app.get("/list",(req,res)=>{
                res.send(data.list)
            })
            
        }
    }
}